<?php

namespace app\common\controller;

use app\common\model\Code;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Controller;


class SmsController extends Controller
{
    public function initialize()
    {
        $accessKeyId  = config('aliyun.accessKeyId');
        $accessSecret = config('aliyun.accessSecret');
        AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
            ->regionId('cn-hangzhou')
            ->asGlobalClient();
    }


    static public function send($mobile)
    {
        $SignName = config('aliyun.SignName');
        $TemplateCode = config('aliyun.TemplateCode');
        $code = rand(1111, 9999);
        $TemplateParam = json_encode(['code' => $code]);
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => $SignName,
                        'TemplateCode' => $TemplateCode,
                        'TemplateParam' => $TemplateParam
                    ],
                ])
                ->request();
            $res = $result->toArray();
            if($res['Code'] == 'OK') {
                if(Code::add($mobile, $code)){
                    return json(['code' => 0, 'msg' => $code]);
                }
            }else{
                return json(['code' => -1, 'msg' => 'error', 'data' => $res]);
            }
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

    public function QuerySendDetails()
    {
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('QuerySendDetails')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumber' => '15949411455',
                        'SendDate' => '20190123',
                        'PageSize' => '10',
                        'CurrentPage' => '1',
//                        'BizId' => '240307348234280824^0',
                    ],
                ])
                ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}